from flask import Flask, render_template
import os
import schedule
import time
import main  # Import main.py functions
import threading

app = Flask(__name__)

# Function to get the list of audio files from the downloads directory
def get_audio_files():
    audio_dir = 'downloads'
    audio_files = []
    for filename in os.listdir(audio_dir):
        if filename.endswith('.mp3'):
            audio_files.append({
                'filename': filename,
                'title': filename[:-4] # Remove .mp3 extension for title
            })
    return audio_files

@app.route('/')
def index():
    audio_files = get_audio_files()
    return render_template('index.html', audio_files=audio_files)

def run_scheduled_downloads():
    while True:
        schedule.run_pending()
        time.sleep(1)

if __name__ == '__main__':
    # Start schedule in a separate thread
    schedule_thread = threading.Thread(target=run_scheduled_downloads)
    schedule_thread.daemon = True
    schedule_thread.start()

    schedule.every(10).minutes.do(main.download_videos) # Schedule download every 10 minutes
    main.download_videos() # Run download_videos once when app starts

    app.run(debug=True, host='0.0.0.0')
